package com.alibaba.citrus.cr.mn.order.center.facade.function.impl;

import com.alibaba.citrus.cr.b2b.trade.order.repository.OrderQueryServiceRepository;
import com.alibaba.citrus.cr.common.enums.ordercenter.DictionaryTypeEnum;
import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.mn.order.center.common.SetOrderTag;
import com.alibaba.citrus.cr.mn.order.center.common.util.AssertUtils;
import com.alibaba.citrus.cr.mn.order.center.common.util.StopWatchUtils;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.DictionaryVerifyAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.function.check.ReturnOrderUpdateParamsBizCheck;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.AbstractOrderBizUpdateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.OrderAtomUpdateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.common.OrderBizUpdateService;
import com.alibaba.citrus.cr.mn.order.center.facade.function.convert.BeanConverter;
import com.alibaba.citrus.cr.mn.order.center.facade.function.convert.OrderUpdateParamsConvertService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderBizIdsRequest;
import com.epoch.app.crb2btradecenter.sdo.OrderLineSDO;
import com.epoch.app.crb2btradecenter.sdo.OrderSDO;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomUpdateRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomUpdateResponse;
import com.epoch.app.mnordercenter.orderbaserequest.OrderBizUpdateRequest;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName SalesOrderBizCreateServiceImpl
 * @description: TODO
 * @date 2023/05/16 14:04
 * @version: 1.0
 */
@Service("returnOrderBizUpdateService")
public class ReturnOrderBizUpdateServiceImpl extends AbstractOrderBizUpdateService implements OrderBizUpdateService<OrderBizUpdateRequest, OrderAtomUpdateRequest, OrderAtomUpdateResponse> {
    private static final Log log = Log.getLogger(ReturnOrderBizUpdateServiceImpl.class);

    @Resource(name = "returnOrderAtomUpdateService")
    private OrderAtomUpdateService returnOrderAtomUpdateService;
    @Resource
    private OrderUpdateParamsConvertService orderUpdateParamsConvertService;
    @Resource
    private DictionaryVerifyAdapter dictionaryVerifyAdapter;
    @Resource
    private OrderQueryServiceRepository orderQueryServiceRepository;
    @Resource
    private ReturnOrderUpdateParamsBizCheck returnOrderUpdateParamsBizCheck;
    @Override
    public void preHandleRequestParams(OrderBizUpdateRequest bizUpdateRequest) {
        AssertUtils.isTrue(StringUtils.isBlank(bizUpdateRequest.getFromSys()), "OC-01-001-01-15-001", "来源系统编码");
        AssertUtils.isTrue(StringUtils.isBlank(bizUpdateRequest.getBusinessType()), "OC-01-001-01-15-001", "业态编码");
        AssertUtils.isTrue(StringUtils.isBlank(bizUpdateRequest.getBusinessUnitCode()), "OC-01-001-01-15-001", "业务单元编码");
        AssertUtils.isTrue(StringUtils.isBlank(bizUpdateRequest.getSalesOrderNo()), "OC-01-001-01-15-001", "退货订单号");

        AssertUtils.lengthCheck(bizUpdateRequest.getFromSys(), 50, true, "OC-01-001-01-15-004", "来源系统编码");
        AssertUtils.lengthCheck(bizUpdateRequest.getBusinessType(), 10, true, "OC-01-001-01-15-004", "业态编码");
        AssertUtils.lengthCheck(bizUpdateRequest.getBusinessUnitCode(), 50, true, "OC-01-001-01-15-004", "业务单元编码");
        AssertUtils.lengthCheck(bizUpdateRequest.getSalesOrderNo(), 50, true, "OC-01-001-01-15-004", "退货订单单号");

        dictionaryVerifyAdapter.verifyDictionary(DictionaryTypeEnum.FROM_SYS.getCode(), bizUpdateRequest.getFromSys(), new FunctionException("OC-01-001-01-15-006", "来源系统编码"));
        dictionaryVerifyAdapter.verifyDictionary(DictionaryTypeEnum.BUSINESS_TYPE.getCode(), bizUpdateRequest.getBusinessType(), new FunctionException("OC-01-001-01-15-006", "业态编码"));
        dictionaryVerifyAdapter.verifyDictionary(DictionaryTypeEnum.BUSINESS_UNIT_CODE.getCode(), bizUpdateRequest.getBusinessUnitCode(), new FunctionException("OC-01-001-01-15-006", "业态编码"));
        //退货订单没有活动，没有信贷校验，不用库存校验，
        bizUpdateRequest.setCheckCredit(Boolean.FALSE);
        bizUpdateRequest.setCheckStock(Boolean.FALSE);
        orderUpdateParamsConvertService.convert(bizUpdateRequest, SetOrderTag.RETURN);
        super.preHandleRequestParams(bizUpdateRequest);

    }

    @Override
    public void paramsInvalidCheck(OrderBizUpdateRequest bizBatchUpdateRequest) {
        StopWatchUtils.start("订单中心商业修改", "paramsInvalidCheck");
        returnOrderUpdateParamsBizCheck.paramsInvalidCheck(Lists.newArrayList(bizBatchUpdateRequest), Lists.newArrayList());
        StopWatchUtils.stop();
    }

    @Override
    public OrderAtomUpdateResponse assembleBizBaseInfo(OrderBizUpdateRequest orderBizUpdateRequest) {
        // 查询db订单数据，用来回填信息
        OrderSDO orderSDO = getOrderSDO(orderBizUpdateRequest, orderBizUpdateRequest.getSalesOrderNo(), true);
        Map<String, OrderLineSDO> lineSDOMap = Optional.ofNullable(orderSDO.getOrderLineSDOS()).orElse(Lists.newArrayList()).stream().collect(Collectors.toMap(OrderLineSDO::getSerialNumber, v -> v));
        orderBizUpdateRequest.getOrderDetails().forEach(line -> {
            OrderLineSDO orderLineSDO = lineSDOMap.get(line.getLineNum());
            if (StringUtils.isNotBlank(line.getLineNum()) && Objects.nonNull(orderLineSDO)) {
                line.setProductCode(orderLineSDO.getScItemSDO().getScItemOutCode());
            }
        });
        return super.assembleBizBaseInfo(orderBizUpdateRequest);
    }

    @Override
    public OrderAtomUpdateRequest convertAtomRequest(OrderBizUpdateRequest updateRequest) {
        OrderAtomUpdateRequest atomUpdateRequest = new OrderAtomUpdateRequest();
        BeanConverter.convert(updateRequest, atomUpdateRequest);
        return atomUpdateRequest;
    }

    @Override
    public OrderAtomUpdateResponse processAtomAbility(OrderAtomUpdateRequest atomCreateRequest, OrderAtomUpdateResponse responses) {
        // 非空时异常直接返回
        if (Objects.isNull(responses)) {
            responses = returnOrderAtomUpdateService.update(atomCreateRequest);
            log.info("修改退货订单原子能力返回结果 Request={}, Result={}",
                    JSON.toJSONString(atomCreateRequest), JSONArray.toJSONString(responses));
        }
        return responses;
    }

    @Override
    public String getOrderTag() {
        return SetOrderTag.RETURN;
    }

    private OrderSDO getOrderSDO(OrderBizUpdateRequest orderBizUpdateRequest, String saleOrderNo, boolean needLines) {
        QueryByOrderBizIdsRequest queryByOrderBizIdsRequest = QueryByOrderBizIdsRequest.builder()
                .fromSys(orderBizUpdateRequest.getFromSys())
                .businessType(Integer.valueOf(orderBizUpdateRequest.getBusinessType()))
                .businessUnitOutCode(orderBizUpdateRequest.getBusinessUnitCode())
                .orderBizIds(Collections.singletonList(saleOrderNo))
                .build();
        List<OrderSDO> orderSDOList = orderQueryServiceRepository.queryByOrderBizIds(queryByOrderBizIdsRequest, needLines);
        if (orderSDOList.size() != 1 || !orderBizUpdateRequest.getOrderCategoryCode().equals(orderSDOList.get(0).getOrderCategoryCode())) {
            throw new FunctionException("OC-01-001-01-16-016", "");
        }
        return orderSDOList.get(0);
    }
}
